package com.secneo.appshare.threads;

import java.io.IOException;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;

import com.secneo.appshare.R;
import com.secneo.appshare.api.RemoteApi.CommentInfo;
import com.secneo.appshare.api.impl.RemoteApiImpl;
import com.secneo.appshare.common.Constants;
import com.secneo.appshare.common.Util;

public class GetAppCommentsThread extends Thread{

	private String package_name;
	private int number;
	private String uid;
	private boolean installed_not_addicted;
	private Context ctx;
	private Handler handler;
	private boolean running = true;
	private CommentInfo commentInfo ;
	private int count ;
	private String timeStamp ;
	

	public GetAppCommentsThread(Context ctx, Handler handler, String package_name, 
			int number, String uid, boolean installed_not_addicted, 
			int count, String timeStamp) {
		this.package_name = package_name;
		this.number = number;
		this.uid = uid;
		this.installed_not_addicted = installed_not_addicted;
		this.ctx = ctx;
		this.handler = handler;
		this.count = count ;
		this.timeStamp = timeStamp ;
		commentInfo = null;
	}
	
	public synchronized void stopRun(){
		running = false;
		this.interrupt();

	}
	
	public CommentInfo getCommentInfo() {
		return commentInfo;
	}
	
	public void run(){
		if(!running)	return ;
		RemoteApiImpl rai = new RemoteApiImpl() ;
		commentInfo = rai.getApplicationComments(
				ctx, package_name, number, uid, installed_not_addicted, 
				count, timeStamp) ;
		
		if(commentInfo != null){
			handler.sendEmptyMessage(Constants.MODE_GET_APP_COMMENTS_FINISH) ;
			if(!running)	return ;
			int count = commentInfo.commentList.size() ;
			for(int i = 0 ; i < count ; ++i){
				try {
					Drawable d ;
					if(commentInfo.commentList.get(i).user_icon.contains("buildin")){
						d = Util.getDrawableFromAsset(
								ctx, commentInfo.commentList.get(i).user_icon) ;
					} else {
						d = Util.getDrawableFromCache(
								ctx, commentInfo.commentList.get(i).user_icon) ;
					}
					if(d == null) {
						d = ctx.getResources().getDrawable(R.drawable.some_user) ;
					}
					commentInfo.commentList.get(i).user_icon_drawable = d ;
				} catch (IOException e) {
					commentInfo.commentList.get(i).user_icon_drawable = 
							ctx.getResources().getDrawable(R.drawable.some_user) ;
					e.printStackTrace();
				}
				handler.sendEmptyMessage(Constants.MODE_GET_APP_COMMENTS_IMG_FINISH) ;
			}
		} else {
			handler.sendEmptyMessage(Constants.MODE_GET_APP_COMMENTS_NET_ERROR) ;
		}
		
	}
	
}
